package tr.com.netgis;

import java.util.Date;

import tr.com.netgis.pojo.NGLocation;
import tr.com.netgis.util.Constants;
import tr.com.netgis.util.Status;
import tr.com.netgis.util.Utility;
import tr.com.netgis.web.SetLocationRequest;
import tr.com.netgis.web.SetLocationResponse;
import tr.com.netgis.web.SetLocationsRequest;
import tr.com.netgis.web.SetLocationsResponse;
import tr.com.netgis.web.WebServisCaller;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.ServiceConnection;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Test operation and other logs
 * @author NetGis
 * 
 */
public class AboutActivity extends Activity {

	static enum Command {
		SET_LOC, SET_LOCS
	}

	private TextView txtAboutView;
	private TextView txtTestResultView;
	private TextView txtStatusView;
	private Button btnTestSetLocation;
	private Button btnTestSetLocations;

	private static final String TAG = "ABOUT";
	private SetLocationApi api;
	private Handler handler;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.about);
		txtAboutView = (TextView) findViewById(R.id.ng_about_txtAboutView);
		txtTestResultView = (TextView) findViewById(R.id.ng_about_txtTestResultView);
		txtStatusView = (TextView) findViewById(R.id.ng_about_txtStatusView);

		
		btnTestSetLocation = (Button) findViewById(R.id.ng_about_btnTestSetLocation);
		btnTestSetLocations = (Button) findViewById(R.id.ng_about_btnTestSetLocations);

		final Activity ctx = this;

		class TestTask extends AsyncTask<Command, Void, String> {

			protected String doInBackground(Command... comms) {
				if (comms[0].equals(Command.SET_LOC))
					return testSetLocation();
				else if (comms[0].equals(Command.SET_LOCS))
					return testSetLocations();
				return "tanımsız komut";
			}

			protected void onProgressUpdate(Void... progress) {
			}

			protected void onPostExecute(String result) {
				// mesajPanosu.setText(result);
				txtTestResultView.setText(result);
				Toast toast = Toast.makeText(ctx, result, 3000);
				toast.show();
				dismissProgress();

			}
		}
		;

		this.btnTestSetLocation.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				dialog = ProgressDialog.show(AboutActivity.this, "",
						"Birkaç saniye bekleyiniz, setLocation çağrılıyor...",
						true);
				new TestTask().execute(Command.SET_LOC);
			}
		});

		this.btnTestSetLocations.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				dialog = ProgressDialog.show(AboutActivity.this, "",
						"Birkaç saniye bekleyiniz, setLocations çağrılıyor...",
						true);
				new TestTask().execute(Command.SET_LOCS);
			}
		});

		handler = new Handler();
		bindService(Constants.SET_LOCATION_SERVICE_INTENT, serviceConnection, 0);
	}

	ProgressDialog dialog;

	private void dismissProgress() {
		dialog.dismiss();
	}

	private String testSetLocation() {
		NGLocation loc = new NGLocation(null);
		loc.setLon(39.91301961);
		loc.setLat(40.91301961);
		loc.setSpeed(1.233f);
		loc.setTarihSaat(new Date().getTime());
		loc.setStatus(Status.UYGULAMA_ACILDI);

		SetLocationRequest request = new SetLocationRequest(loc);
		request.setDeviceCode(Utility.getDeviceId());
		request.setServerUrl(SharedPrefs.getInstance()
				.getServerUrl());
		// request.setSessionId(NetMobileLocationSharedPrefs.getInstance(ctx).getSessionId());
		// //TODO session id test için
		SetLocationResponse response = WebServisCaller.callWebService(request);
		FileLogger.log(response.getResponseXml() != null ? response.getResponseXml() : response.toString());
		Log.i(TAG, response.toString());
		return response.toString();

	}

	private String testSetLocations() {
		NGLocation loc1 = new NGLocation(null);
		loc1.setLon(39.91301961);
		loc1.setLat(40.91301961);
		loc1.setSpeed(0.2323f);
		loc1.setTarihSaat(new Date().getTime());

		NGLocation loc2 = new NGLocation(null);
		loc2.setLon(39.91301961);
		loc2.setLat(40.91301961);
		loc2.setSpeed(1.4533f);
		loc2.setTarihSaat(new Date().getTime());
		
		NGLocation loc3 = new NGLocation(null);
		loc3.setStatus(Status.HAREKET_EDIYOR);
		loc3.setLon(39.92201961);
		loc3.setLat(40.88801961);
		loc3.setSpeed(5.4533f);
		loc3.setTarihSaat(new Date().getTime());

		SetLocationsRequest request = new SetLocationsRequest(new NGLocation[] {
				loc1, loc2, loc3});
		request.setDeviceCode(Utility.getDeviceId());
		request.setServerUrl(SharedPrefs.getInstance()
				.getServerUrl());
		// request.setSessionId(NetMobileLocationSharedPrefs.getInstance(ctx).getSessionId());
		// //TODO session id test için
		SetLocationsResponse response = WebServisCaller.callWebService(request);
		FileLogger.log(response.getResponseXml() != null ? response.getResponseXml() : response.toString());
		Log.i(TAG, response.toString());
		return response.toString();

	}

	@Override
	protected void onPause() {
		Log.i(TAG, "Pause");
		super.onPause();
	}

	@Override
	protected void onRestart() {
		Log.i(TAG, "Restart");
		super.onRestart();
	}

	@Override
	protected void onResume() {
		Log.i(TAG, "Resume");
		super.onResume();
		txtStatusView.setText("GPS enabled: " + Utility.isGPSEnabled(this));		
	}

	@Override
	protected void onStart() {
		Log.i(TAG, "Start");
		super.onStart();
	}

	@Override
	protected void onStop() {
		Log.i(TAG, "Stop");
		super.onStop();
	}

	private ServiceConnection serviceConnection = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			Log.i(TAG, "Service connection established");

			// that's how we get the client side of the IPC connection
			api = SetLocationApi.Stub.asInterface(service);
			try {
				api.addListener(collectorListener);
			} catch (RemoteException e) {
				Log.e(TAG, "Failed to add listener", e);
			}

			updateLogView();
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			Log.i(TAG, "Service connection closed");
		}
	};

	private SetLocationListener.Stub collectorListener = new SetLocationListener.Stub() {
		@Override
		public void handleLocationsUpdated() throws RemoteException {
			updateLogView();
		}
	};

	private void updateLogView() {
		// doing this in a Handler allows to call this method safely from any
		// thread
		// see Handler docs for more info
		handler.post(new Runnable() {
			@Override
			public void run() {
				try {
					SetLocationResult result = api.getResult();
					String about = result.getAbout();
					if (about == null)
						about = "Mesaj boş";
					Log.i(TAG + " From Service", about);
					// if (result.getTweets().isEmpty()) {
					// if (result.getmData() == null ||
					// result.getmData().equals("")) {
					if (result.getLocation() == null) {
						txtAboutView.setText("...\n");
					} else {
						txtAboutView.setText(about + "\n" + result.getmData());
					}
				} catch (Throwable t) {
					Log.e(TAG, "Error while updating the UI with about", t);
				}
			}
		});
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		try {
			api.removeListener(collectorListener);
			unbindService(serviceConnection);
		} catch (Throwable t) {
			// catch any issues, typical for destroy routines
			// even if we failed to destroy something, we need to continue
			// destroying
			Log.w(TAG, "Failed to unbind from the service", t);
		}

		Log.i(TAG, "Activity destroyed");
	}


}
